// XMLLib version 1 - ProjectSorter example
//
// Author
//
//   Thomas Koos (info@muetze1.de)
//   www.muetze1.de
//
// License
//
//   This Source Code Form is subject to the terms of the Mozilla Public
//   License, v. 1.1. If a copy of the MPL was not distributed with this
//   file, You can obtain one at http://mozilla.org/MPL/1.1/.
//
// Revision
//
//   $Id: SorterConfig.pas 25 2014-12-07 23:20:06Z muetze1@gmail.com $
//

unit SorterConfig;

interface

type
    // configuration class
  TSorterConfig = class
  private
    fStartSortingAtLevel: integer;
    fSortNodes: boolean;
    fSortAttributes: boolean;
    fSortNodesUseAttrValueOnEqualNodes: boolean;

  public
    constructor Create;

      // load configuration
    function LoadFromFile(const aConfigFilename: string): boolean;

      // sort only beginning with node level x
    property StartSortingAtLevel: integer read fStartSortingAtLevel;
      // sort nodes?
    property SortNodes: boolean read fSortNodes;
      // on equal nodes: sort by attribute values?
    property SortNodesUseAttrValueOnEqualNodes: boolean read fSortNodesUseAttrValueOnEqualNodes;
      // sort attributes?
    property SortAttributes: boolean read fSortAttributes;
  end;

implementation

uses
  XMLLib;                               // for TXMLLib

{ TSorterConfig }

constructor TSorterConfig.Create;
begin
    // set default values
  fStartSortingAtLevel := 1;
  fSortNodes := true;
  fSortNodesUseAttrValueOnEqualNodes := true;
  fSortAttributes := true;
end;

function TSorterConfig.LoadFromFile(const aConfigFilename: string): boolean;
var
  lConfigFile: TXMLLib;
  lNode: TXMLNode;
  lAttr: TXMLAttribute;
begin
  result := false;

  try
    lConfigFile := TXMLLib.Create;
    try
        // loading configuration file
      if lConfigFile.LoadFromFile(aConfigFilename) then
      begin
          // find specific node
        lNode := lConfigFile.GetNodeFromPath('SorterConfig/Sorting/Nodes');

          // found node?
        if assigned(lNode) then
        begin
            // sort nodes?
          fSortNodes := lNode.Value.AsBoolean;

            // locate attribute on node
          lAttr := lNode.Attributes.ItemByName['StartLevel'];
          if assigned(lAttr) then
            fStartSortingAtLevel := lAttr.Value.AsIntegerDefault(1);

            // use attr value on equal nodes
          lAttr := lNode.Attributes.ItemByName['UseAttrValuesWhenEqual'];
          if assigned(lAttr) then
            fSortNodesUseAttrValueOnEqualNodes := lAttr.Value.AsBoolean;
        end;

          // find specific node
        lNode := lConfigFile.GetNodeFromPath('SorterConfig/Sorting/Attributes');

          // found node?
        if assigned(lNode) then
        begin
            // sort attributes?
          fSortAttributes := lNode.Value.AsBoolean;
        end;

        result := true;
      end;
    finally
      lConfigFile.Free;
    end;
  except
    result := false;
  end;
end;

end.
